import React, { useState, useEffect } from 'react';
import { Typography, Spin, Empty, Button, List, Card, Modal } from 'antd';
import axios from 'axios';

const { Title, Text, Link } = Typography;

// 定义从 backend/routers/studentActivityRouter/showSactivity.js 的 /studentAttended/:studentId 接口获取的记录接口
interface AttendedActivityRecord {
  id: number; // student_activity record ID
  student_id: number; // 学生ID
  activity_id: number; // 活动ID
  status: 'registered' | 'attended' | 'missed'; // 状态
  points_awarded: string; // 实际获得的积分 (后端返回可能是字符串)
  register_time: string; // 报名时间
  attend_time: string | null; // 签到/出席时间
}

// 定义从 /api/activityDetail/:activityId 接口获取的活动详情接口 (简化)
interface ActivityDetail {
  id: number;
  title: string; // 活动标题
  club_id: number; // 社团ID
  type: string; // 活动类型
  description: string; // 活动描述
  location: string; // 活动地点
  created_at: string; // 创建时间
  // ... 可以根据需要添加其他活动详情字段
}

// 合并 AttendedActivityRecord 和 ActivityDetail 的接口，用于页面显示
interface DisplayAttendedActivity {
  studentActivityId: number; // student_activity record ID
  activityId: number; // 活动ID
  activityTitle: string; // 活动标题
  pointsAwarded: number; // 实际获得的积分 (转换为数字)
  attendTime: string; // 签到/出席时间 (格式化)
  club_id: number; // 社团ID
  type: string; // 活动类型
  description: string; // 活动描述
  location: string; // 活动地点
  createdAt: string; // 创建时间 (格式化)
}

const HistoryPointPage: React.FC = () => {
  const [attendedActivities, setAttendedActivities] = useState<DisplayAttendedActivity[]>([]);
  const [totalPoints, setTotalPoints] = useState<number>(0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedActivityDetails, setSelectedActivityDetails] = useState<DisplayAttendedActivity | null>(null);

  useEffect(() => {
    const fetchHistoryPoints = async () => {
      try {
        setLoading(true);
        setError(null);

        const userInfo = localStorage.getItem('userInfo');
        if (!userInfo) {
          setError('请先登录获取积分历史');
          setLoading(false);
          return;
        }
        const studentId = JSON.parse(userInfo).id; // 获取学生ID

        if (!studentId) {
          setError('无法获取学生信息，请重新登录');
          setLoading(false);
          return;
        }

        console.log(`Fetching attended activities for student ID: ${studentId}`);

        // 1. 调用接口获取学生已参加的活动记录
        const attendedResponse = await axios.get<{
          success: boolean;
          data: {
            total: number;
            page: number;
            pageSize: number;
            totalPoints?: string; // 后端接口可能返回总积分，这里使用可选属性
            records: AttendedActivityRecord[];
          };
          message?: string;
        }>(`http://localhost:5000/api/studentAttended/${studentId}`);

        console.log('Attended Activities Response:', attendedResponse.data);

        if (attendedResponse.data.success && attendedResponse.data.data && Array.isArray(attendedResponse.data.data.records)) {
          const attendedRecords = attendedResponse.data.data.records;

          // 2. 对每个已参加的活动记录，获取活动详情
          const activitiesWithDetailsPromises = attendedRecords.map(async (record) => {
            try {
              const activityDetailResponse = await axios.get<{
                success: boolean;
                data: ActivityDetail;
                message?: string;
              }>(`http://localhost:5000/api/activityDetail/${record.activity_id}`);

              if (activityDetailResponse.data.success && activityDetailResponse.data.data) {
                // 格式化出席时间
                const attendTime = record.attend_time ? new Date(record.attend_time).toLocaleString('zh-CN') : '-';
                const activityDetails = activityDetailResponse.data.data;
                return {
                  studentActivityId: record.id,
                  activityId: record.activity_id,
                  activityTitle: activityDetails.title,
                  pointsAwarded: parseFloat(record.points_awarded) || 0, // 将积分转为数字
                  attendTime: attendTime,
                  club_id: activityDetails.club_id,
                  type: activityDetails.type,
                  description: activityDetails.description,
                  location: activityDetails.location,
                  createdAt: new Date(activityDetails.created_at).toLocaleString('zh-CN'), // 格式化创建时间
                } as DisplayAttendedActivity;
              } else {
                console.error(`获取活动详情失败 (ID: ${record.activity_id}):`, activityDetailResponse.data.message);
                return null; // 获取详情失败，返回 null
              }
            } catch (error) {
              console.error(`获取活动详情失败 (ID: ${record.activity_id}):`, error);
              return null; // 获取详情失败，返回 null
            }
          });

          const activitiesWithDetails = await Promise.all(activitiesWithDetailsPromises);

          // 过滤掉获取详情失败的记录
          const validAttendedActivities = activitiesWithDetails.filter(item => item !== null) as DisplayAttendedActivity[];

          setAttendedActivities(validAttendedActivities);

          // 3. 计算总积分
          // 优先使用后端返回的总积分，如果没有，则在前端计算
          const calculatedTotalPoints = attendedResponse.data.data.totalPoints 
            ? parseFloat(attendedResponse.data.data.totalPoints) 
            : validAttendedActivities.reduce((sum, activity) => sum + activity.pointsAwarded, 0);
            
          setTotalPoints(calculatedTotalPoints);

        } else {
          console.error('获取已参加活动记录失败或数据格式不正确:', attendedResponse.data);
          setError('获取积分历史失败：数据格式不正确');
        }
      } catch (error: any) {
        console.error('获取积分历史失败:', error);
        setError(error.response?.data?.message || '获取积分历史失败');
      } finally {
        setLoading(false);
      }
    };

    fetchHistoryPoints();
  }, []); // 空依赖数组，只在组件挂载时运行一次

  const handleTitleClick = (activity: DisplayAttendedActivity) => {
    console.log('Activity clicked:', activity); // 添加日志
    setSelectedActivityDetails(activity);
    setIsModalVisible(true);
  };

  const handleModalClose = () => {
    setIsModalVisible(false);
    setSelectedActivityDetails(null);
  };

  if (loading) {
    return (
      <div style={{ padding: '24px', textAlign: 'center' }}>
        <Spin size="large" />
        <p style={{ marginTop: '16px' }}>加载中...</p>
      </div>
    );
  }

  if (error) {
    return (
      <div style={{ padding: '24px', textAlign: 'center' }}>
        <Title level={2}>积分历史</Title>
        <Empty description={error} />
        {/* 可以添加一个刷新按钮 */}
        {/* <Button type="primary" onClick={fetchHistoryPoints} style={{ marginTop: '16px' }}>
          重试
        </Button> */}
      </div>
    );
  }

  return (
    <div style={{ padding: '24px' }}>
      <Title level={2}>我的积分历史</Title>
      <div style={{ marginBottom: '24px' }}>
        <Text strong>总获得积分：</Text>
        <Text type="success" style={{ fontSize: '20px' }}>{totalPoints.toFixed(2)}</Text>
      </div>

      <Card title="已参加活动列表" bordered={false}>
        {attendedActivities.length === 0 ? (
          <Empty description="暂无参加的活动记录" />
        ) : (
          <List
            itemLayout="horizontal"
            dataSource={attendedActivities}
            renderItem={(item) => (
              <List.Item>
                <List.Item.Meta
                  title={
                    <a onClick={() => handleTitleClick(item)} style={{ cursor: 'pointer' }}>
                      {item.activityTitle}
                    </a>
                  }
                  description={
                    <>
                      <p>参加时间：{item.attendTime}</p>
                      <p>获得积分：{item.pointsAwarded.toFixed(2)}</p>
                    </>
                  }
                />
              </List.Item>
            )}
          />
        )}
      </Card>

      <Modal
        title={selectedActivityDetails?.activityTitle}
        open={isModalVisible}
        onCancel={handleModalClose}
        footer={[
          <Button key="back" onClick={handleModalClose}>
            关闭
          </Button>
        ]}
      >
        {selectedActivityDetails && (
          <div>
            <p><strong>社团ID：</strong>{selectedActivityDetails.club_id}</p>
            <p><strong>活动类型：</strong>{selectedActivityDetails.type}</p>
            <p><strong>描述：</strong>{selectedActivityDetails.description}</p>
            <p><strong>地点：</strong>{selectedActivityDetails.location}</p>
            <p><strong>创建时间：</strong>{selectedActivityDetails.createdAt}</p>
            <p><strong>参加时间：</strong>{selectedActivityDetails.attendTime}</p>
            <p><strong>获得积分：</strong>{selectedActivityDetails.pointsAwarded.toFixed(2)}</p>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default HistoryPointPage;
